package cn.jsl.estwo;

import cn.jsl.utils.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;


public class esTwo {

    /**
     * @Description: 批量添加数据
     * @Author: Director
     * @Date: 2022/7/23 0:02
     * @return: void
     **/
    @Test
    public void testBatch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "这是我敲的第二遍ES!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }

    /**
     * 综合案例
     *  - 查询用户表
     * - name包含：我在源码
     * - age在1~12之间
     * - sex=1
     * - 每页大小2
     * - 从2页开始查
     * - 按照age倒序
     */
    @Test
    public void test1() throws Exception{
        //得到es链接
        TransportClient client = ESClientUtil.getClient();
        //得到查询的指定文档对象
        SearchRequestBuilder pethome = client.prepareSearch("pethome");
        //得到bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //得到must和match,并把match设置到must再设置到bool中
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "这是");
        boolQuery.must(matchQuery);
        //设置filter
        boolQuery.filter(QueryBuilders.termQuery("sex",1))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));
        //设置分页
        pethome.setSize(2);
        pethome.setFrom(6);
        //设置排序
        pethome.addSort("age",SortOrder.DESC);
        //得到查询结果进行打印
        SearchHit[] hits = pethome.get().getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
        //关流
        client.close();
    }
}
